﻿using System;
using QuailServices;
using QuailServices.QuailDataServiceReference;

namespace Quail
{
    /// <summary>
    /// The remote control host to use for a given test
    /// </summary>
    public class RemoteControlHost : IDisposable
    {
        internal RemoteControlHost(GetNextRemoteControlHostResult result)
        {
            Host = result.HostName;
            Port = result.HostPort ?? 4444;
            HostKey = result.HostKey ?? 0;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="RemoteControlHost"/> class.
        /// </summary>
        /// <param name="host">The host.</param>
        /// <param name="port">The port.</param>
        public RemoteControlHost(string host, int port)
        {
            Host = host;
            Port = port;
            HostKey = 0;
        }

        ~RemoteControlHost()
        {
            Dispose(false);
        }

        /// <summary>
        /// Gets the host.
        /// </summary>
        /// <value>The host.</value>
        public string Host
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the port.
        /// </summary>
        /// <value>The port.</value>
        public int Port
        {
            get;
            private set;
        }

        internal int HostKey
        {
            get;
            private set;
        }

        /// <summary>
        /// Returns the RemoteControlHost as Host:Port
        /// </summary>
        /// <returns>A string</returns>
        public override string ToString()
        {
            return Host + ":" + Port;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (HostKey != 0)
                {
                    using (var service = QuailDataServiceFactory.CreateClient())
                    {
                        service.ReleaseRemoteControlHost(HostKey);
                    }
                }
            }
        }
    }
}
